<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row class="query-form">
        <Col span="8">
            <FormItem label="二级集团：">
                <two-level-org org-code v-model="form1.twoLevelOrgCode" />
            </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="公司名称：">
            <company-select v-model="form1.companyName" style="width:100%" />
            <!-- <cascaderDom class="query-form-el" style="width: 100%;" ref="querys"
                         @setOrgInfo="setQueryOrgId" @setOrgname="setQueryOrgName"
                         :orgTree="true"></cascaderDom> -->
          </FormItem>
        </Col>
        <Col span="8" v-if="!switchFlag">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text"  >展开∨</Button>
          <Button @click="reset" class="ivu-btn-reset" style="margin-left: 2px">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query()">查询</Button>
        </Col>
        <Col span="8" v-else>
          <FormItem label="相关方名称：">
            <Input type="text" v-model="form1.relatedCompanyName"/>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="入场事由：">
            <Select  v-model="form1.reasonsId"  class="query-form-el" style="width: 100%;">
              <Option v-for="item in reasons" :value="item.codingCodeId"
                      :key="item.codingCodeId">{{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8" offset="8">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text"  >收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset"   >重置</Button>
          <Button   class="ivu-btn-query"   icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <download-button :api="exportUrl" :queryForm='form1' />
        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight" :loading="loading" size="small" class="table" no-data-text="没有查询到相关数据!"
    @on-sort-change="sortChange" show-summary :summary-method="(data) => this.gAmountTo(data,['personNum'])"
           highlight-row stripe border :columns="columns1" width="100%" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              style="float: right" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>

    <Modal :transfer=false v-model="model1" :width=981  :title="add?'外来人员安全告知新增':'外来人员安全告知修改'" :styles="{height:'559px'}"  class-name='limit-height-dialog'
           @on-cancel="onCancel">
      <div>
        <Form style="margin-left: 10px" ref='InputData' :model="InputData" :rules="ruleCustom" :show-message="false"
              label-position="top">
          <Row style="line-height: 28px;">
              <Col span='7' >
                <FormItem label='相关方名称：' prop="relatedCompanyName">
                  <Input v-model="InputData.relatedCompanyName" show-word-limit :maxlength="50"/>
                </FormItem>
              </Col>

              <Col span='7' offset="1">
                <FormItem label='公司名称：' prop="companyId">
                  <cascaderDom class="query-form-el" style="width: 100%;" ref="trainOrg"
                               @setOrgInfo="setOrgId" @setOrgName="setOrgName"
                               :currentOrgId="InputData.companyId"
                               :currentOrgName="InputData.companyName" :orgTree="true"></cascaderDom>
                </FormItem>
              </Col>

              <Col span='7' :offset="1">
                <FormItem label='入场事由：' prop="reasonsId">
                  <Select  v-model="InputData.reasonsId"  class="query-form-el" style="width: 100%;">
                    <Option v-for="item in reasons" :value="item.codingCodeId"
                            :key="item.codingCodeId">{{ item.codingName }}
                    </Option>
                  </Select>
                </FormItem>
              </Col>


              <Col span='7' >
                <FormItem label='填报人：' prop="userName">
                  <Input v-model="InputData.userName" :readonly="true"/>
                </FormItem>
              </Col>
              <Col span='7' :offset="1">
                <FormItem label='填报时间：' prop="createDate">
                  <Input  v-model="InputData.createDate" :readonly="true" />
                </FormItem>
              </Col>

              <Col span='7' :offset="1">
                <FormItem label='填报人电话：' prop="phone">
                  <Input v-model="InputData.phone" />
                </FormItem>
              </Col>

            <Col span='7' >
              <FormItem label='人员数量：' prop="personNum">
                <InputNumber :min="0" v-model="InputData.personNum" style="width: 100%"></InputNumber>
              </FormItem>
            </Col>
            <Col span='7' :offset="1">
              <FormItem label='管理单位：' prop="manageUnit">
                <Input  v-model="InputData.manageUnit" show-word-limit :maxlength="50"/>
              </FormItem>
            </Col>

            <Col span='7' :offset="1">
              <FormItem label='参观事项：' prop="visit">
                <Input v-model="InputData.visit" show-word-limit :maxlength="100"/>
              </FormItem>
            </Col>
              <Col span="23">
                <FormItem label="相关附件(上传告知卡)：">
                  <div>
                    <Upload ref="upload"
                            :before-upload="beforeUpload"
                            :show-upload-list="true"
                            :max-size="10240"
                            multiple
                            type="drag"
                            :action="fileUrl">
                      <div style="padding: 10px">
                        <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                        <p>点击将文件拖拽到这里上传</p>
                        <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                      </div>
                    </Upload>
                  </div>
                  <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                    <a @click="downloadFile(InputData.id,item)">{{ item.fileName }}</a>
                    <Button type="text" icon="md-trash" @click="remove1(item.id)"
                            style="margin-left: 5px;margin-bottom: 3px"/>
                  </div>
                </FormItem>
              </Col>

           <!-- <Col span="8" class="query-form">
              <Button class="ivu-btn-add" icon="md-add" @click="addItemInfo()">新增人员</Button>
            </Col>
            <Col span="23" style="margin-top: 10px;margin-bottom: 10px">
              <Table height="300"  :loading="loading" size="small" class="table" no-data-text="没有查询到相关数据!"
                     highlight-row stripe border :columns="columns3" width="100%" :data="evaluateItem">
              </Table>
            </Col>-->
          </Row>
        </Form>
      </div>
      <div slot="footer">
        <Button class='ivu-btn-save' :loading="buttonLoading" @click="submit('InputData')">确定</Button>
        <Button class='ivu-btn-cancel' @click="onCancel">取消</Button>
      </div>
    </Modal>

    <Modal :transfer=false v-model="model3" :width=1100  title="外来人员安全告知详情"
           @on-cancel="onCancel" :styles="{height:'559px'}"  class-name='limit-height-dialog'>
      <Form style="margin-left: 10px" :model="InputData" label-position="top">
        <Row style="line-height: 42px;">

          <Col span='7' >
            <Row type="flex" justify="start" class="code-row-bg">
              <Col span="7">相关方名称：</Col>
              <Col span="17">{{InputData.relatedCompanyName}}</Col>
            </Row>
<!--            <span></span>-->
          </Col>

          <Col span='7' offset="1">
            <Row>
              <Col span="6">公司名称：</Col>
              <Col span="18">{{InputData.companyName}}</Col>
            </Row>
<!--            <span></span>-->
          </Col>
          <Col span='7'  offset="1">
            <span>入场事由：{{reasonsMap[InputData.reasonsId]}}</span>
          </Col>
        </Row>
        <Row class="detail-background-clor" style="line-height: 42px;">
          <Col span='7' >
            <span>填报人：{{InputData.userName}}</span>
          </Col>

          <Col span='7' offset="1">
            <span>填报时间：{{renderViewDate(InputData.createDate)}}</span>
          </Col>
          <Col span='7' offset="1">
            <span>填报人电话：{{InputData.phone}}</span>
          </Col>
        </Row>
        <Row style="line-height: 42px;">
          <Col span='7' >
            <span>人员数量：{{InputData.personNum}}</span>
          </Col>
          <Col span='7' :offset="1">
            <span>管理单位：{{InputData.manageUnit}}</span>
          </Col>
          <Col span='7' :offset="1">
            <span>参观事项：{{InputData.visit}}</span>
          </Col>
        </Row>
        <Row style="line-height: 42px;">
          <Col span="23">
            <FormItem label="相关附件(上传告知卡)：">
              <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                <a @click="downloadFile(InputData.id,item)">{{ item.fileName }}</a>
              </div>
            </FormItem>
          </Col>
        </Row>
       <!-- <Row style="line-height: 42px;">
          <Col span='23' style="margin-top: 10px;margin-bottom: 10px">
            <Table height="300" class="table"  :loading="loading" size="small" no-data-text="没有查询到相关数据!"
                   highlight-row stripe border :columns="columns10" width="100%" :data="evaluateItem">
            </Table>
          </Col>
        </Row>-->
      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="onCancel">关闭</Button>
      </div>
    </Modal>
    <Modal :transfer=false v-model="model4" :width=700  :title="addItem?'人员新增':'人员修改'"
           @on-cancel="model4=false;InputItemData={}">
      <div>
        <Form ref='InputItemData' :model="InputItemData" :rules="ruleCustom1" label-position="top">
          <Row style="line-height: 42px;">
            <Col span='11'>
              <FormItem label='姓名：' prop="informName">
                <Input v-model="InputItemData.informName" />
              </FormItem>
            </Col>
            <Col span='11' offset="1">
              <FormItem label='性别：' prop="informSex">
                <Select  v-model="InputItemData.informSex"  class="query-form-el" style="width: 100%;">
                  <Option value="0">男</Option>
                  <Option value="1">女</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span='11' >
              <FormItem label='手机：' prop="informPhone">
                <Input v-model="InputItemData.informPhone" />
              </FormItem>
            </Col>
            <Col span='11' offset="1">
              <FormItem label='职务：' prop="informPost">
                <Input v-model="InputItemData.informPost" />
              </FormItem>
            </Col>
           <Col span='23'>
              <FormItem label='备注：' >
                <Input v-model="InputItemData.informNote" type="textarea"
                       :autosize="{minRows:2,maxRows:5}"/>
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
      <div slot="footer">
        <Button class='ivu-btn-save' :loading="buttonLoading" @click="submitItem('InputItemData')">确定</Button>
        <Button class='ivu-btn-cancel' @click="model4=false;InputItemData={}">取消</Button>
      </div>
    </Modal>

    <Modal :transfer=false v-model="model5"  :width=600 title="人员详情"
           @on-cancel="model5=false" >
      <Form class="modal-view-detail" :model="InputItemData" label-position="top" >
        <Row style="line-height: 42px;">
          <Col span='11'>
            <span>姓名：{{InputItemData.informName}}</span>
          </Col>
          <Col span='11' offset="1">
            <span>性别：{{InputItemData.informSex == '0'?'男':'女'}}</span>
          </Col>
        </Row>
        <Row style="line-height: 42px;" class="detail-background-clor">
          <Col span='11'>
            <span>手机：{{InputItemData.informPhone}}</span>
          </Col>
          <Col span='11' offset="1">
            <span>职务：{{InputItemData.informPost}}</span>
          </Col>
        </Row>
        <Row  style="line-height: 42px;">
          <Col span='23'>
            <span>备注：{{InputItemData.informNote}}</span>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="model5=false">关闭</Button>
      </div>
    </Modal>

  </Layout>
</template>

<script>
import {Api} from '../../../api/index.js'
import {sessionStorage} from '../../../common/cacheUtils.js';
import cascaderDom from '../../../components/cascader-dom.vue';
import {formatDate} from "@/tools";

export default {
  components: {cascaderDom},
  data() {
    return {
      exportUrl: Api.queryInform + '/export',
      certificateDate1:'',
      reviewDate1:'',
      switchFlag:false,
      certificateDate:['',''],
      reviewDate:['',''],
      brandList:[
        {
          name:'男',
          value:'0',
        },
        {
          name:'女',
          value:'1',
        }
      ],
      addItem:false,
      InputItemDate:{},
      model4:false,
      dataTable:[],
      tableHeight: '',loading: false,
      validityTerm:'',
      form1: {
        agreementName: '',
        contractorName: '',
      },
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      model5:false,
      ruleCustom: {
        relatedCompanyName: [{message: '请填写相关方名称', required: true, trigger: 'change'}],
        companyId: [{
          validator: (rule, value, callback) => {
            if ( this.InputData.companyId == null ||  this.InputData.companyId == ''||  this.InputData.companyId == undefined) {
              callback('请选择公司名称')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        reasonsId: [{message: '请选择入场事由', required: true, trigger: 'change'}],
        userName: [{message: '请填写填报人', required: true, trigger: 'change'}],
        createDate: [{message: '请填写填报时间', required: true, trigger: 'change'}],
          personNum: [{message: '请填写人员数量', required: true, trigger: 'change',type:'number'}],
          manageUnit: [{message: '请填写管理单位', required: true, trigger: 'change'}],
          visit: [{message: '请填写参观事项', required: true, trigger: 'change'}],
        phone: [{
          validator: (rule, value, callback) => {
            if(!(/^1[3456789]\d{9}$/.test(this.InputData.phone))){
              callback('请填写填报人电话');
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
      },
      ruleCustom1: {
        informName: [{
          message: '  ',
          required: true,
          trigger: 'change'
        }],
        informSex: [{
          validator: (rule, value, callback) => {
            if (value == null || value == ''|| value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        informPhone: [{
          validator: (rule, value, callback) => {
            if(!(/^1[3456789]\d{9}$/.test(this.InputItemData.informPhone))){
              callback(' ');
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
        informPost: [{
          validator: (rule, value, callback) => {
            if (value == null || value == ''|| value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      evaluateItem: [],
      columns3: [
        {
          type: 'index',
          title: '序号',
          width: 80,
          align: 'center',
        },
        {
          minWidth: 100,
          title: '姓名',
          align: 'center',
          key: 'informName',
        },
        {
          minWidth: 120,
          title: '性别',
          align: 'center',
          key: 'informSex',
          render: (h, params) => {
            return h('span', params.row.informSex == '0' ? '男':'女')
          }
        },
        {
          minWidth: 150,
          title: '手机',
          align: 'center',
          key: 'informPhone',
        },
        {
          minWidth: 150,
          title: '职务',
          align: 'center',
          key: 'informPost',
        },
        {
          minWidth: 150,
          title: '备注',
          align: 'center',
          key: 'informNote',
          tooltip:true
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 200,
          align: 'center',
          render: (h, params) => {

            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                },
                on: {
                  click: () => {
                    this.InputItemData = params.row;
                    this.model5 = true;
                  }
                }
              }, '详情'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                },
                on: {
                  click: () => {
                    this.InputItemData = JSON.parse(JSON.stringify(params.row));
                    this.model4 = true;
                    this.addItem = false;
                    this.index = params.index;
                  }
                }
              }, '修改'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color: 'red',
                },
                on: {
                  click: () => {
                    this.evaluateItem.splice(params.index,1);
                  }
                }
              }, '删除')
            ]);
          }
        }
      ],
      index:null,
      currentUser: JSON.parse(sessionStorage('userId').get('userId')),
      columns1: [
        {title: '序号', width: 75, align: 'center', render: (h, params) => {
          if(params.index == 0) return h('span', "汇总");
          return h('span', params.index-1 + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
        }},
        {title: '相关方名称', align: 'center', key: 'relatedCompanyName', minWidth: 150,},
        {title: '公司名称', align: 'center', key: 'companyName', minWidth: 150,},
        {title: '入场事由', align: 'center', key: 'reasonsId', minWidth: 150, render: (h, params) => {
            return h('span', this.reasonsMap[params.row.reasonsId])}},
          {title: '人员数量', align: 'center', key: 'personNum', minWidth: 100,},
          {title: '管理单位', align: 'center', key: 'manageUnit', minWidth: 100,},
          {title: '参观事项', align: 'center', key: 'visit', minWidth: 100,},
        {title: '填报人', align: 'center', key: 'userName', minWidth: 100,},
        {title: '填报时间', align: 'center', key: 'createDate', sortable: "custom",minWidth: 100, render:this.renderCellDate,},
        {title: '填报人电话', align: 'center', key: 'phone', minWidth: 100,},
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 200,
          align: 'center',
          render: (h, params) => {
            if (params.row.id=='-1') {
                return;
            }
            if(this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId ||this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                    ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined){
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                  },
                  on: {
                    click: () => {
                      this.InputData = params.row;
                      this.evaluateItem = params.row.saOutsidersInformItemList;
                      this.getFiles();
                      this.model3 = true;
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',

                  },
                  on: {
                    click: () => {
                      this.evaluateItem = params.row.saOutsidersInformItemList;
                      this.InputData = params.row;
                      this.$set(this.InputData,'createDate',formatDate(new Date(this.InputData.createDate), "yyyy-MM-dd"))
                      this.getFiles();
                      this.model1 = true;
                      this.add = false;
                    }
                  }
                }, '修改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                    color: 'red'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '数据删除',
                        content: '<p>确定删除该条信息</p>',
                        okText: '确认',
                        onOk: () => {
                          this.deleteData(params.row);
                        },
                        cancelText: '取消'
                      });
                    }
                  }
                }, '删除')
              ]);
            }else{
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                  },
                  on: {
                    click: () => {
                      this.InputData = params.row;
                      this.yearlyDate = this.formatDate(new Date(this.InputData.yearlyDate), 'yyyy-MM-dd');
                      this.certificateDate1 = this.formatDate(new Date(this.InputData.certificateDate), 'yyyy-MM-dd');

                      this.reviewDate1 = this.formatDate(new Date(this.InputData.reviewDate), 'yyyy-MM-dd');
                      this.validityTerm = this.formatDate(new Date(this.InputData.validityTerm), 'yyyy-MM-dd');
                      this.evaluateItem = params.row.saOutsidersInformItemList;
                      this.model3 = true;
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '修改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '删除')
              ]);
            }

          }
        }
      ],
      reasons:[],
      reasonsMap:{},
      updateParam:null,
      effectiveDate:'',
      approvalDate:'',
      add: false,
      model1: false,
      model3: false,
      contractTermDate1:'',
      evaluationPeriodDate1:'',
      yearlyDate:'',

      fileUrl: Api.interestedPartiesUserFile,
      InputData: {},
      buttonLoading: false,
      InputItemData:{},
      uploadList: [],

      pageModel2: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
        contractorName: ''
      },
      contractor: [],
      model2: false,
    }
  },
  mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 193;
    this.selectCodingSort();
    this.query()
  },
  computed: {
    columns10() {
      const columns = [...this.columns3];
      const columns10=[]
      columns.forEach(item=>{
        if (item.title != '操作'){
          columns10.push(item)
        }
      });
      return columns10
    },
  },
  methods: {
    sortChange(data) {
		    if (data.order === 'asc'||data.order ==='desc') {
		        let order = data.key
		        this.form1.dynamicSort = order +' '+ data.order
		        this.query()
		    }
		},
    selectCodingSort() {
      this.$http.get(Api.queryCodeDetailBySortId + '/inform-000001', {params: {}}).then((res) => {
        this.reasons = res.data.data;
        this.reasonsMap = {};
        this.reasons.forEach(row => {
          this.reasonsMap[row.codingCodeId] = row.codingName;
        })
      });
    },

    switchQuery(flag){
      this.switchFlag = flag;
      if(!this.switchFlag){
        this.tableHeight = window.innerHeight - 220;
      }else{
        this.tableHeight = window.innerHeight - 315;
      }
    },
    submitItem(name){
      let _this = this;
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (_this.addItem){
            _this.evaluateItem.push(this.InputItemData);
            _this.model4 = false;
          } else{
            let index = _this.index;
            Vue.set(_this.evaluateItem,index,_this.InputItemData)
            _this.model4 = false;
          }

        }else{
          this.$Message.error('请填报完整!');
        }
      })
    },
    addItemInfo(){
      this.addItem = true;
      this.InputItemData = {};
      this.model4 = true
    },
    danxuan(row, index) {
      this.InputData.contractorId = row.contractorId
      this.InputData.contractorName = row.contractorName
      this.model2 = false
      this.model1 = true
    },

    selectContractor() {
      this.model2 = true
      this.contractor = []
      let data = {
        startPage: this.pageModel2.currentPage,
        size: this.pageModel2.pageSize,
        contractorName: this.pageModel2.contractorName
      }
      data = Object.assign(data);
      let url = Api.interestedPartiesAccountList
      this.$http.get(url, {params: data}).then((res) => {
        console.log(res.data);
        this.contractor = res.data.data.data;
        this.pageModel2.total = res.data.data.totalSize;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    setOrgId(data) {
      this.InputData.companyId = data[data.length - 1];
    },
    setOrgName(data) {
      this.InputData.companyName = data;
    },
    setQueryOrgId(data) {
      this.form1.companyId = data[data.length - 1];
    },
    setQueryOrgName(data) {
      this.form1.companyName = data;
    },


    downloadFile(perfId, file) {
      let url = this.fileUrl + '/file/' + file.id;
      this.$http.get(url, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        console.log(res)
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    remove1(id) {
      let url = this.fileUrl + '/file/' + id;
      this.$http.delete(url).then((res) => {
        this.getFiles()
      })
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    beforeUpload(file) {
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.InputData.id + '/files/inform'
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功")
          this.getFiles();
        }
      })
      return false
    },
    async getFiles() {
      let url = this.fileUrl + '/' + this.InputData.id + '/files/inform'
      await this.$http.get(url).then((res) => {
        if (res.data.result == "success") {
          console.log(res.data)
          this.uploadList = res.data.data
        }
      })
    },

    onCancel() {
      this.InputData = {};
      this.evaluateItem = [];
      this.model1 = false;
      this.model3 = false;
      this.uploadList = [];
      this.query()
    },
    submit(name) {
        let validateFieldArr = Object.keys(this.ruleCustom)
        let _self = this;
        Promise.all(validateFieldArr.map(item => {
            return new Promise(function (resolve, reject) {
                _self.$refs[name].validateField(item, (error) => {
                    resolve(error)
                })
            });
        })).then((data) => {
            // data 里是各个字段的验证错误信息, 如果为空串则认为验证通过, 如果数组里全为空串则所有验证通过
            // 去除数组空值
            data = data.filter(item => item)
            if(!data.length){  //通过验证
                _self.buttonLoading=true
                _self.InputData.saOutsidersInformItemList = _self.evaluateItem;
                if (_self.add) {
                    let url = Api.saveInform;
                    _self.InputData.createOrgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                    _self.InputData.createUsrId = sessionStorage('userId').getObject('userId').userId;
                    _self.$http.post(url, _self.InputData).then((res) => {
                        _self.$Message.success('成功');
                        _self.buttonLoading = false
                        _self.model1 = false
                        _self.query()
                    }).catch(e => {
                        _self.$Message.error('请求失败');
                    })
                } else {
                    let url = Api.updateInform;
                    _self.InputData.createUsrId = sessionStorage('userId').getObject('userId').userId
                    _self.InputData.updateOrgId = sessionStorage('userId').getObject('userId').orgInfo.orgId
                    _self.$http.put(url, _self.InputData).then((res) => {
                        _self.$Message.success('成功');
                        _self.buttonLoading = false
                        _self.model1 = false
                        _self.query()
                    }).catch(e => {
                        _self.$Message.error('请求失败');
                    })
                }
            } else {  //验证不通过 暂时只提示一个
                _self.$Message.error(data[0]);
            }
        })
    },

    deleteData(row) {
      let url = Api.deleteInform + '/' + row.id;
      this.$http.delete(url).then((res) => {
        this.$Message.success('成功');
        this.query()
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    addInfo() {
      this.add = true;
      this.InputData = {};
      this.InputData.personNum=0
      this.InputData.id = this.get_uuid();
      this.InputData.userName = sessionStorage('userId').getObject('userId').userName;
      this.InputData.phone = sessionStorage('userId').getObject('userId').mobileNumber;
      this.InputData.createDate = formatDate(new Date(), "yyyy-MM-dd")
      this.evaluateItem = [];
      this.model1 = true;
    },
    renderViewDate(date) {
      if (!date) return "";
      return formatDate(new Date(date), "yyyy-MM-dd");
    },
    renderCellDate(h, params) {
      let key = params.column.key;
      if (!params.row[key]) return "";
      return h('span', formatDate(new Date(params.row[key]), "yyyy-MM-dd"))
    },
    query() {this.loading = true ;
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        orgId: sessionStorage('userId').getObject('userId').companyId
      };
      if (this.certificateDate[0]!=""&&this.certificateDate[1]!=""){
        this.form1.certificateStartDate =  this.formatDate(new Date(this.certificateDate[0]), 'yyyy-MM-dd');
        this.form1.certificateEndDate = this.formatDate(new Date(this.certificateDate[1]), 'yyyy-MM-dd');
      }
      if (this.reviewDate[0]!=""&&this.reviewDate[1]!=""){
        this.form1.reviewStartDate =  this.formatDate(new Date(this.reviewDate[0]), 'yyyy-MM-dd');
        this.form1.reviewEndDate = this.formatDate(new Date(this.reviewDate[1]), 'yyyy-MM-dd');
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      let url = Api.queryInform
      this.$http.get(url, {params: data}).then((res) => {
        console.log(res.data);
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
        this.loading = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    reset() {
      this.form1 = {}
      this.$refs.querys && this.$refs.querys.resetCurrentOrg();
      this.pageModel2.currentPage = 1;
      this.pageModel2.contractorName = ''
      this.query();
    },
    pageChange1(pageNum) {
      this.pageModel2.currentPage = pageNum;
      this.query();
    },
    pageSizeChange1(pageSize) {
      this.pageModel2.pageSize = pageSize;
      this.query();
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    get_uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";

      let uuid = s.join("");
      let reg = new RegExp("-", "g");
      let a = uuid.replace(reg, "");
      console.log(a);
      return a;
    },
  },
  watch: {
    "model1": function (qw, er) {
      if (qw && this.model1) {
        setTimeout(() => {
          this.$refs.trainOrg.setCurrentOrg();

        }, 100)
      } else {
        this.$refs.trainOrg.resetCurrentOrg();

      }
    },

  },
}
</script>

<style scoped>
@import '../../../index.css';
</style>
